//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;
using OpenLS.Drawing;
using OpenLS.Drawing.UI;
using OpenLS.Drawing.UI.Internals;

namespace OpenLS.Chart.UI
{
    class ThemedElementToFillConverter: IMultiValueConverter
    {
        #region IMultiValueConverter Members

        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            var scheme = StrictConverter.Convert<ColorScheme>(values[0]);
            if (scheme == null)
                return null;
            int seriesIndex = StrictConverter.Convert(values[1], 0);
            if (values.Length <= 2)
                return GetBrush(scheme, seriesIndex, 0, false, null, null); //\\
            return GetBrush(scheme, seriesIndex, StrictConverter.Convert(values[2], 0), StrictConverter.Convert(values[3], false), 
                StrictConverter.Convert<DataPoints>(values[4]), StrictConverter.Convert<FillProperties>(values[5]));
      }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }

        static Brush GetBrush (ColorScheme scheme, int seriesIndex, int valueIndex, bool useValueIndex, 
            DataPoints dataPoints, FillProperties fillProperties)
        {
            bool useTheme = false;
            if (dataPoints != null)
            {
                foreach (DataPoint pt in dataPoints)
                {
                    if (pt.Index == valueIndex)
                    {
                        if (pt.ShapeProperties != null)
                        {
                            if (pt.ShapeProperties.FillProperties == null)
                                useTheme = true;
                            else
                                return FillPropertiesToBrushConverter.FillPropertiesToBrush(
                                    pt.ShapeProperties.FillProperties, scheme, null);
                        }
                    }
                }
            }
            if (!useTheme && fillProperties != null)
            {
                Brush result = FillPropertiesToBrushConverter.FillPropertiesToBrush(fillProperties, scheme, null);
                if (result != null)
                    return result;
            }
            int indexToUse = useValueIndex ? valueIndex : seriesIndex;
            FillPattern pattern = new AccentFillPattern();

            return ColorBaseToBrushConverter.ColorBaseToBrush(pattern.GetColor(indexToUse), scheme);
        }
        #endregion
    }
}
